<template>
  <div>

    <el-form :model="form"
             :rules="rules"
             ref="profileForm"
             label-width="auto"
             v-loading="loading"
             element-loading-text="正在加载"
             element-loading-spinner="el-icon-loading"
             class="profile-box"
    >

      <img src="../../../assets/image/profile-change.png" alt="" style="width: 150px">

      <el-form-item label="账号">
        <el-input type="text" v-model="form.username" disabled/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input type="email" v-model="form.email" disabled/>
      </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="身份" prop="role" style="text-align: left">
              <el-tag effect="dark">众包工人</el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="text-align: left">
            <template #label>
            <span>
              等级
              <el-tooltip placement="top-start">
                <template #content>
                  <div>每月（每月1号24:00点截止指标绩效积累）评定工人等级，等级分为<code>特级-高级-优秀-三星-二星-一星</code>5个等级，新用户为二星<br/>
①每月完成报告数量>20 且 评分为优秀的>50% 且 失信率<5%保级（否则降级，直到最低级）<br/>
②每月完成报告数量50 且 评分为优秀的>50% 且 失信率<1% 的升级<br/>
③任何一个月失信率>10%直接降至最低级。</div>
                </template>
                <el-icon class="el-icon-question"></el-icon>
              </el-tooltip></span>
            </template>
            <el-tooltip placement="top-start">
              <template #content>
                  查看等级历程
              </template>
              <el-tag effect="dark" @click="$router.push('/worker/levelHistory')">{{ level }}</el-tag>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="擅长技能">
        <el-row type="flex">
          <el-select v-model="form.skill" placeholder="请选择擅长技能"  @change="changed=true">
            <el-option label="无" value="none"></el-option>
            <el-option label="功能测试" value="function_test"></el-option>
            <el-option label="性能测试" value="performance_test"></el-option>
            <el-option label="用例设计" value="usecase_design"></el-option>
            <el-option label="异常定位" value="exception_locate"></el-option>
          </el-select>
        </el-row>
      </el-form-item>
      <el-form-item label="任务偏好">
        <el-row type="flex">
          <el-select v-model="form.task_prefer" placeholder="请选择任务偏好"  @change="changed=true">
            <el-option label="无" value="none"></el-option>
            <el-option label="功能测试" value="function_test"></el-option>
            <el-option label="性能测试" value="performance_test"></el-option>
            <el-option label="Bug探索" value="bug_explore"></el-option>
          </el-select>
        </el-row>
      </el-form-item>
      <el-form-item label="余额" >
        <el-row type="flex">
          <el-col :span="4">
            <el-icon v-if="loadingBalance" class="el-icon-loading"></el-icon>
            <span v-else>
              {{ balance }}
            </span>
          </el-col>
          <el-col :span="4">
            <el-button-group>
              <el-button @click="withdraw()" size="mini" type="primary">提现</el-button>
              <el-button @click="transactionDetail()" size="mini" type="primary">账户明细</el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-button style="width: 100px" class="btn" id="register-btn" type="primary" @click="onSubmit">更新</el-button>
      <div style="margin-top: 80px">
        <el-tooltip class="explain" effect="dark" placement="top-start">
          <div slot="content">活跃度获取规则：每日登录+1(仅第一次)，<br/>每次提交报告+5，每次协作/评价报告+2。<br/><br/>活跃度兑换规则：每月1日0:00，系统会自<br/>动按50:1(活跃度：Collect币)的比例兑换您<br/>一月内的活跃度。该兑换行为不会影响您的<br/>活跃度数值。</div>
          <i class="el-icon-s-opportunity"></i>
        </el-tooltip>
        <ActivityView class="activity"></ActivityView>
      </div>

    </el-form>
  </div>

</template>

<script>
import {Debounce} from "@/utils/Debounce.js";
import {updateInfo} from "@/api/profile";
import ActivityView from "@/components/worker/profile/ActivityView";
import {getUserBalance} from "@/api/user";

export default {
  name: 'WorkerInfo',
  components: {
    ActivityView,
  },
  data() {
    return {
      form: {
        username: sessionStorage.getItem('username'),
        email: sessionStorage.getItem('email'),
        role: "worker",
        skill: sessionStorage.getItem("skill"),
        task_prefer: sessionStorage.getItem("taskPrefer"),
        freq_device: sessionStorage.getItem("freqDevice")
      },
      balance: undefined,
      loadingBalance: false,
      rules: {
        skill: [
          {required: true, message: '擅长技能不可为空', trigger: 'change'},
        ],
        task_prefer: [
          {required: true, message: '任务偏好不可为空', trigger: 'change'},
        ],
        /*        freq_device: [
                  {required: true, message: '常用测试环境不可为空', trigger: 'change'},
                ]*/
      },

      loading: true,
      changed: false
    };
  },

  created() {
    this.initProfile();
  },
  computed: {
    level(){
      return sessionStorage.getItem('workerLevel');
    }
  },
  mounted() {
    this.loadBalance();
  },
  methods: {
    initProfile() {
      if(sessionStorage.getItem("skill")==='null')
        this.form.skill='';
      else
        this.form.skill = sessionStorage.getItem("skill");
      if(sessionStorage.getItem("taskPrefer")==='null')
        this.form.task_prefer='';
      else
        this.form.task_prefer = sessionStorage.getItem("taskPrefer");
      /*      if(sessionStorage.getItem("freqDevice")==='null')
              this.form.freq_device='';
            else
              this.form.freq_device = sessionStorage.getItem("freqDevice");*/

      this.loading = false;
    },
    loadBalance(){
      this.loadingBalance = true;
      getUserBalance(sessionStorage.getItem('userid')).then(res => {
        if(res.code === 200){
          this.balance = res.data;
        }else{
          throw new Error(res.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      }).finally(() => {
        this.loadingBalance = false;
      })
    },
    transactionDetail(){
      this.$router.push('/worker/transactionDetail');
    },
    // todo: 更改众包工人特征
    onSubmit: Debounce(function () {
      if (!this.changed) {
        this.$message.error('您并未更改资料，请更改后再试！');
        return;
      }

      this.$refs['profileForm'].validate((valid) => {
        if (valid) {
          sessionStorage.setItem("skill",this.form.skill);
          sessionStorage.setItem("taskPrefer",this.form.task_prefer);
          //sessionStorage.setItem("freqDevice",this.form.freq_device);

          this.handleUpdate(this.form);
        } else {
          this.$message.error('更新失败，请检查您的信息！')
          return false;
        }
      });
    }, 1000),
    async handleUpdate(payload){
      const res = await updateInfo(payload);
      if (res.code === 200) {
        this.$message.success('资料更新成功！');
        await this.$router.push('/worker');
      } else {
        this.$message.error(res.msg);
      }
    },
    withdraw(){
      this.$router.push('/worker/withdraw');
    }

  }
}
</script>


<style scoped>
.explain{
  margin-left: 15%;
}
.activity{
  margin-left: 5%;
}


.profile-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}

a {
  margin-right: 30%;
}
.profile-box {
  overflow: visible;
  border: 1px solid #DCDFE6;
  width: 1000px;
  margin: 5% auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 8px #909399;
  background-color: #f8f8f8;
}
</style>
